package com.android.base_network.interceptor

import android.os.Build
import android.text.TextUtils
import com.android.base_network.BuildConfig
import com.android.base_network.CacheKeys
import com.android.base_network.HeaderKeys
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.DeviceUtils
import com.blankj.utilcode.util.LanguageUtils
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ScreenUtils
import okhttp3.Interceptor
import okhttp3.Response

class AddHeadParamsInterceptor : Interceptor {

    private var appUniqueDeviceId = ""

    override fun intercept(chain: Interceptor.Chain): Response {
        if (TextUtils.isEmpty(appUniqueDeviceId)) {
            val boolean = SPUtils.getInstance().getBoolean(CacheKeys.isAgreePrivacy)
            if (boolean) {
                appUniqueDeviceId = DeviceUtils.getUniqueDeviceId()
            }
        }
        // 以拦截到的请求为基础创建一个新的请求对象，然后插入Header
        val request = chain.request().newBuilder()
            .addHeader(HeaderKeys.authorization,SPUtils.getInstance().getString(CacheKeys.token))
            .addHeader(HeaderKeys.firebaseToken, SPUtils.getInstance().getString(CacheKeys.firebaseToken))
            .addHeader(HeaderKeys.os, "Android")
            .addHeader(HeaderKeys.osVersion, "Android ${Build.VERSION.RELEASE}")
            .addHeader(HeaderKeys.deviceId, DeviceUtils.getUniqueDeviceId())
            .addHeader(HeaderKeys.manufacturer, DeviceUtils.getManufacturer().uppercase())
            .addHeader(HeaderKeys.model, DeviceUtils.getModel())
            .addHeader(HeaderKeys.contentType, "application/x-www-form-urlencoded")
            .addHeader(
                HeaderKeys.resolution,
                "${ScreenUtils.getScreenWidth()}*${ScreenUtils.getScreenHeight()}"
            )
            .addHeader(HeaderKeys.appVersion, AppUtils.getAppVersionName())
            .addHeader(
                HeaderKeys.userAgent,
                "${AppUtils.getAppName()}-${AppUtils.getAppVersionName()}"
            )
            .addHeader(HeaderKeys.appId, BuildConfig.app_id)
            .addHeader(HeaderKeys.lon, "")  //经度
            .addHeader(HeaderKeys.lat, "")  //纬度
            .addHeader(HeaderKeys.sysLanguage, LanguageUtils.getSystemLanguage().language)
            .addHeader(HeaderKeys.appLanguage, LanguageUtils.getAppContextLanguage().language)
            .build()
        // 开始请求
        return chain.proceed(request)

    }
}